<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-model="dialogVisible" title="零件清单" width="1200" :before-close="handleClose">
    <el-descriptions>
      <el-descriptions-item label="部段名称：">{{ datas.section }}</el-descriptions-item>
      <el-descriptions-item label="主部段：">{{ datas.mainSection }}</el-descriptions-item>
      <el-descriptions-item label="部段所在层次：">{{ datas.ata }}</el-descriptions-item>
      <el-descriptions-item label="所属机型：">{{ datas.aircraftModel }}</el-descriptions-item>
      <el-descriptions-item label="所属批次：">{{ datas.track }}</el-descriptions-item>
      <el-descriptions-item label="数据产生日期：">{{ datas.createTime }}</el-descriptions-item>
    </el-descriptions>
    <div class="title">强度数模清单</div>
    <el-form inline :model="dialogForm" class="p-t-2" size="small">
      <el-form-item prop="code" label="零组件编号" label-width="82px">
        <el-input v-model="dialogForm.code" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item prop="name" label="零件名称">
        <el-input v-model="dialogForm.name" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="initData">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="p-b-2">
      <el-button type="primary" size="small" @click="exportData">数据导出</el-button>
    </div>
    <el-table v-load="loading" :data="tableDatas" row-key="id">
      <el-table-column type="expand">
        <template #default="props">
          <div m="4">
            <el-table :data="props.row.children">
              <el-table-column label="零件编号" prop="code" />
              <el-table-column label="零件名称" prop="name" />
              <el-table-column label="版本号" prop="version">
                <template #default="scope">
                  <div v-if="scope.row.editable">
                    <el-input v-model="scope.row.version" style="width: 100px" @blur="handleVersionNumBlur(scope.row)"></el-input>
                    <el-input v-model="scope.row.versionNum" style="width: 100px" @blur="handleVersionNumBlur(scope.row)"></el-input>
                  </div>
                  <span v-else>{{ scope.row.version }}{{ scope.row.versionNum }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="text" @click="handleVersion(scope.row)">版本修改</el-button>
                  <el-button type="text" @click="handleDelete(props.row.children, scope.row.id, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column prop="groupCode" label="组件编号"></el-table-column>
      <el-table-column prop="groupName" label="组件名称"></el-table-column>
      <el-table-column prop="groupVersion" label="版本号">
        <template #default="scope">
          <div v-if="scope.row.editable">
            <el-input v-model="scope.row.groupVersion"></el-input>
          </div>
          <span v-else>{{ scope.row.groupVersion }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button type="text" @click="handleVersion(scope.row)">版本修改</el-button>
          <el-button type="text" @click="handleDelete(scope.row.id, scope.$index)">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination v-show="total > 0" v-model:page="dialogForm.pageNum" v-model:limit="dialogForm.pageSize" :total="total" @pagination="initData" />
    <template #footer>
      <div class="dialog-footer">
        <el-button v-loading="btnLoading" @click="handleClose">取消</el-button>
        <el-button v-loading="btnLoading" type="primary" @click="handleSave"> 确认并保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="PartStrengthDialog" lang="ts">
import { getStrengthDetailV2, exportStrengthV2, modifyStrengthV2 } from '@/api/bomCompareTool/strengthModelList/index';
import { t } from 'vxe-table';
const { proxy } = getCurrentInstance();
const emit = defineEmits(['on-sure']);
const dialogVisible = ref(false);
const datas = reactive({
  id: '',
  section: '',
  mainSection: '',
  ata: '',
  aircraftModel: '',
  track: '',
  createTime: '',
  srcDesc: '',
  summary: ''
});
const loading = ref(false);
const total = ref(0);
const dialogForm = reactive({
  code: '',
  name: '',
  track: '',
  groupType: '',
  aircraftModel: '',
  pageNum: 1,
  pageSize: 10
});
const btnLoading = ref(false);
const ids = ref([]);
const changeDatas = ref([]);
const tableDatas = ref([]);
const initData = async () => {
  loading.value = true;
  const res = await getStrengthDetailV2(dialogForm).catch(() => {
    loading.value = false;
  });
  const datas = res.rows
    .filter((item) => !ids.value.includes(item.id))
    .map((item) => {
      const data = changeDatas.value.find((el) => el.id === item.id);
      if (data) {
        item.version = data.version;
        item.versionNum = data.versionNum;
        item.groupVersion = data.groupVersion;
      }
      return item;
    });
  const groupData = datas.reduce((grouped, item) => {
    const key = `${item.groupName}-${item.groupCode}-${item.groupVersion}`;
    grouped[key] = grouped[key] || [];
    grouped[key].push(item);
    return grouped;
  }, {});
  tableDatas.value = [];
  for (const key in groupData) {
    const arr = key.split('-');
    const obj = {
      groupName: arr[0],
      groupCode: arr[1],
      groupVersion: arr[2],
      children: groupData[key]
    };
    tableDatas.value.push(obj);
  }
  console.log(tableDatas.value);
  total.value = res.total;
};
const openDialog = (data) => {
  dialogForm.aircraftModel = data.aircraftModel;
  dialogForm.track = data.track;
  dialogForm.groupType = data.groupType;
  for (const key in datas) {
    datas[key] = data[key];
  }
  initData();
  ids.value = [];
  changeDatas.value = [];
  dialogVisible.value = true;
};
const handleClose = () => {
  dialogVisible.value = false;
};
const handleVersionNumBlur = (row) => {
  const index = changeDatas.value.findIndex((item) => item.id === row.id);
  if (index > -1) {
    changeDatas.value.splice(index, 1, row);
  } else {
    changeDatas.value.push(row);
  }
};
const downloadFile = (res, fileName) => {
  const blob = new Blob([res]);
  const objUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', objUrl);
  link.setAttribute('download', fileName);
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
// 下载文件
const exportData = () => {
  const obj = {
    aircraftModel: datas.aircraftModel,
    id: datas.id
  };
  exportStrengthV2(obj).then((res) => {
    const contentDisposition = res.headers['content-disposition'];
    if (contentDisposition) {
      // 使用正则表达式提取filename（注意：这里的正则需要根据实际Content-Disposition的格式进行调整）
      const filename = contentDisposition.match(/filename="?([^"]+)"?/)[1];
      const fileName = decodeURIComponent(filename);
      downloadFile(res.data, fileName);
    }
  });
};
const handleVersion = (row) => {
  row.editable = true;
};
const handleDelete = (arr, id, index) => {
  arr.splice(index, 1);
  ids.value.push(id);
};
const handleSave = async () => {
  btnLoading.value = true;
  const obj = {
    srcStrengthBomId: datas.id,
    deleteDetailIds: ids.value,
    modifyDetails: changeDatas.value
  };
  const res = await modifyStrengthV2(obj).catch(() => {
    btnLoading.value = false;
  });
  proxy?.$modal.msgSuccess('保存成功!');
  btnLoading.value = false;
  handleClose();
};
defineExpose({
  openDialog
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: center;
}
.title {
  font-size: 14px;
  font-weight: 700;
  line-height: 48px;
}
</style>
